import React from 'react';
import { RegisterCommand, withPropsAPI } from 'gg-editor';

const RightDrawer = React.lazy(() => import('../common/Drawer'));
class EditCommand extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  showDrawer = () => {
    this.setState({
      visible: true,
      title: '',
      model: '',
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const that = this;
    const { propsAPI } = this.props;

    const config = {
      // 是否进入列队，默认为 true
      queue: true,

      // 命令是否可用
      enable(/* editor */) {
        return true;
      },

      // 正向命令逻辑
      execute(/* editor */) {
        let res = propsAPI.save();


        if (that.props.type === 'end') {
          return;
        }
        let { title, modal, index, id } = propsAPI.getSelected()[0].model;
        if (!index) {
          for (let i of res.nodes) {
            if (id === i.id) {
              index = i.index;
            }
          }
        }
        that.setState({
          title,
          model: modal,
          visible: true,
          nodeId: id,
        });
      },

      // 反向命令逻辑
      back(/* editor */) {

      },

      // 快捷按键配置
      shortcutCodes: [
        ['metaKey', 'n'],
        ['ctrlKey', 'n'],
      ],
    };
    const { title, model, visible, nodeId } = this.state;
    const { dialogId } = this.props;

    return (
      <div>
        <RegisterCommand name="editCommand" config={config} />
        <RightDrawer
          title={title}
          model={model}
          visible={visible}
          onClosed={this.onClose}
          nodeIds={nodeId}
          dialogId={dialogId}
        />
      </div>
    );
  }
}

export default withPropsAPI(EditCommand);
